package com.portal.framework.webutil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.portal.framework.dao.ISearchForm;
import com.portal.framework.page.PagerResult;
import com.portal.framework.util.JsonUtil;
import com.portal.framework.util.SystemConfig;

public abstract class BaseAction extends ActionSupport implements ModelDriven {
	public   SystemConfig config=SystemConfig.getInstance();
	private SearchFormCommonDAO searchFormCommonDAO;

	public SearchFormCommonDAO getSearchFormCommonDAO() {
		return searchFormCommonDAO;
	}

	public void setSearchFormCommonDAO(SearchFormCommonDAO searchFormCommonDAO) {
		this.searchFormCommonDAO = searchFormCommonDAO;
	}
	
	
	@SuppressWarnings("unchecked")
	protected <T> PagerResult<T> findByCondition(Class<T> clazz,
			ISearchForm searchForm) {
		return searchFormCommonDAO.findByCondision(clazz, searchForm);
	}
	
	@SuppressWarnings("unchecked")
	protected <T> PagerResult<T> findByCondisionAndCast(Class<?> searchClazz,
			ISearchForm searchForm, Class<T> retClazz) {
		return searchFormCommonDAO.findByCondisionAndCast(searchClazz,searchForm,retClazz);
	}
	
	public Map getSession() {
		return ActionContext.getContext().getSession();
	}
	
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	protected  HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
	/**
	 * 转换json字符串并输出到客户端
	 * 
	 * @param list
	 */
	public  void outputDateinfo(List<?> list) {
		try {
			String listString = JsonUtil.toJsonString(list);
			HttpServletResponse rs = ServletActionContext.getResponse();
			rs.setContentType("text/html");
			rs.setCharacterEncoding("utf-8");
			rs.getWriter().println(listString);
			rs.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 字符串输出到客户端
	 */
	public void outputDateinfo(String obj) {
		try {
			HttpServletResponse rs = ServletActionContext.getResponse();
			rs.setContentType("text/html");
			rs.setCharacterEncoding("utf-8");
			rs.getWriter().println(obj);
			rs.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String changeURLDecoder(String obj){
		try {
			obj = URLDecoder.decode(obj, "UTF-8").trim();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
